S<template>
  <div class="style-factor-container">

    <div class="header">
      <h2>风格因子管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="createFactor">新建风格因子</el-button>
        <el-button @click="exportFactors">导出</el-button>
      </div>
    </div>

    <div class="main-content">
      <!-- 左侧：因子列表 -->
      <div class="factor-list">
        <div class="list-header">
          <h3>风格因子列表</h3>
          <!-- 多条件搜索 -->
          <div class="search-filters">
            <el-row :gutter="10">
              <el-col :span="6">
                <el-input 
                  v-model="searchFilters.name" 
                  placeholder="搜索因子名称" 
                  prefix-icon="el-icon-search"
                  clearable
                  @input="onSearch"
                ></el-input>
              </el-col>
              <el-col :span="6">
                <el-input 
                  v-model="searchFilters.code" 
                  placeholder="搜索因子代码" 
                  prefix-icon="el-icon-search"
                  clearable
                  @input="onSearch"
                ></el-input>
              </el-col>
              <el-col :span="4">
                <el-select 
                  v-model="searchFilters.styleType" 
                  placeholder="风格类型" 
                  clearable
                  @change="onSearch"
                >
                  <el-option label="价值风格" value="VALUE"></el-option>
                  <el-option label="成长风格" value="GROWTH"></el-option>
                  <el-option label="质量风格" value="QUALITY"></el-option>
                  <el-option label="动量风格" value="MOMENTUM"></el-option>
                  <el-option label="小盘风格" value="SMALL_CAP"></el-option>
                  <el-option label="大盘风格" value="LARGE_CAP"></el-option>
                  <el-option label="自定义风格" value="CUSTOM"></el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select 
                  v-model="searchFilters.algorithm" 
                  placeholder="算法类型" 
                  clearable
                  @change="onSearch"
                >
                  <el-option label="加法" value="ADD"></el-option>
                  <el-option label="减法" value="SUBTRACT"></el-option>
                  <el-option label="乘法" value="MULTIPLY"></el-option>
                  <el-option label="除法" value="DIVIDE"></el-option>
                  <el-option label="加权加法" value="WEIGHTED_ADD"></el-option>
                  <el-option label="加权乘法" value="WEIGHTED_MULTIPLY"></el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-select 
                  v-model="searchFilters.enabled" 
                  placeholder="状态" 
                  clearable
                  @change="onSearch"
                >
                  <el-option label="启用" :value="true"></el-option>
                  <el-option label="禁用" :value="false"></el-option>
                </el-select>
              </el-col>
            </el-row>
          </div>
        </div>

        <el-table 
          :data="filteredFactors" 
          @row-click="selectFactor"
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column prop="factorName" label="因子名称" width="80"></el-table-column>
          <el-table-column prop="factorCode" label="因子代码" width="80"></el-table-column>
          <el-table-column prop="styleType" label="风格类型" width="80">
            <template #default="{ row }">
              <el-tag :type="getStyleTagType(row.styleType)">{{ getStyleName(row.styleType) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="formula" label="算法" width="100">
            <template #default="{ row }">
              <el-tag size="small">{{ getAlgorithmName(row.formula) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="enabled" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.enabled ? 'success' : 'info'">
                {{ row.enabled ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="400">
            <template #default="{ row }">
              <div style="display: flex; align-items: center; gap: 10px;">
                <el-input
                    v-model="row.fundCode"
                    placeholder="输入基金代码计算风格因子值"
                    style="width: 200px;"
                    size="small"
                ></el-input>
                <el-button size="mini" type="primary" @click.stop="calculateFactor(row)" :loading="calculating">计算</el-button>
                <el-button size="mini" @click.stop="editFactor(row)">编辑</el-button>
                <el-button size="mini" type="danger" @click.stop="deleteFactor(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 右侧：因子配置 -->
      <div class="factor-config">
        <h3>{{ selectedFactor.id ? '编辑风格因子' : '新建风格因子' }}</h3>
        
        <el-form :model="selectedFactor" label-width="100px" class="factor-form">
          <el-form-item label="因子名称" required>
            <el-input v-model="selectedFactor.factorName" placeholder="输入因子名称"></el-input>
          </el-form-item>
          
          <el-form-item label="因子代码" required>
            <el-input v-model="selectedFactor.factorCode" placeholder="输入因子代码"></el-input>
          </el-form-item>
          
          <el-form-item label="风格类型" required>
            <el-select v-model="selectedFactor.styleType" placeholder="选择风格类型" @change="onStyleTypeChange">
              <el-option-group label="传统风格">
                <el-option label="价值风格" value="VALUE"></el-option>
                <el-option label="成长风格" value="GROWTH"></el-option>
                <el-option label="质量风格" value="QUALITY"></el-option>
                <el-option label="动量风格" value="MOMENTUM"></el-option>
                <el-option label="规模风格" value="SIZE"></el-option>
              </el-option-group>
              <el-option-group label="新兴风格">
                <el-option label="ESG风格" value="ESG"></el-option>
                <el-option label="低波动风格" value="LOW_VOLATILITY"></el-option>
                <el-option label="高股息风格" value="HIGH_DIVIDEND"></el-option>
                <el-option label="科技风格" value="TECHNOLOGY"></el-option>
                <el-option label="消费风格" value="CONSUMER"></el-option>
              </el-option-group>
              <el-option-group label="自定义风格">
                <el-option label="自定义风格" value="CUSTOM"></el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          
          <el-form-item label="算法类型" required>
            <el-select v-model="selectedFactor.algorithm" placeholder="选择算法" @change="onAlgorithmChange">
              <el-option-group label="基础运算">
                <el-option label="加法" value="ADD"></el-option>
                <el-option label="减法" value="SUBTRACT"></el-option>
                <el-option label="乘法" value="MULTIPLY"></el-option>
                <el-option label="除法" value="DIVIDE"></el-option>
              </el-option-group>
              <el-option-group label="统计运算">
                <el-option label="均值" value="MEAN"></el-option>
                <el-option label="加权平均" value="WEIGHTED_MEAN"></el-option>
                <el-option label="标准差" value="STD"></el-option>
                <el-option label="方差" value="VARIANCE"></el-option>
                <el-option label="中位数" value="MEDIAN"></el-option>
              </el-option-group>
              <el-option-group label="数据处理">
                <el-option label="排序" value="RANK"></el-option>
                <el-option label="标准化" value="ZSCORE"></el-option>
                <el-option label="缩尾处理" value="WINSORIZE"></el-option>
                <el-option label="对数变换" value="LOG"></el-option>
                <el-option label="差分" value="DIFF"></el-option>
              </el-option-group>
              <el-option-group label="高级算法">
                <el-option label="主成分分析" value="PCA"></el-option>
                <el-option label="因子分析" value="FACTOR_ANALYSIS"></el-option>
                <el-option label="聚类分析" value="CLUSTERING"></el-option>
                <el-option label="回归分析" value="REGRESSION"></el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          
          <el-form-item label="基础因子" required>
            <el-select 
              v-model="selectedFactor.baseFactors" 
              multiple 
              placeholder="选择基础因子"
              filterable
              @change="onBaseFactorsChange"
            >
              <el-option 
                v-for="factor in availableFactors" 
                :key="factor.code" 
                :label="factor.name" 
                :value="factor.code"
              ></el-option>
            </el-select>
            <div class="factor-count-info">
              已选择 {{ selectedFactor.baseFactors ? selectedFactor.baseFactors.length : 0 }} 个因子
            </div>
          </el-form-item>
          
          <el-form-item label="算子配置" required>
            <div class="operator-config">
              <div v-for="(factor, index) in selectedFactor.baseFactors" :key="index" class="operator-item">
                <div class="operator-header">
                  <span class="factor-name">{{ getFactorName(factor) }}</span>
                  <el-button size="mini" type="danger" @click="removeFactor(index)" v-if="selectedFactor.baseFactors.length > 1">删除</el-button>
                </div>
                <div class="operator-content">
                  <el-select 
                    v-model="selectedFactor.operators[index]" 
                    placeholder="选择算子"
                    style="width: 120px; margin-right: 10px;"
                  >
                    <el-option label="加法" value="ADD"></el-option>
                    <el-option label="减法" value="SUBTRACT"></el-option>
                    <el-option label="乘法" value="MULTIPLY"></el-option>
                    <el-option label="除法" value="DIVIDE"></el-option>
                    <el-option label="加权加法" value="WEIGHTED_ADD"></el-option>
                    <el-option label="加权乘法" value="WEIGHTED_MULTIPLY"></el-option>
                  </el-select>
                  <el-input-number
                    v-model="selectedFactor.weights[index]"
                    :min="0"
                    :max="1"
                    :precision="4"
                    :step="0.1"
                    placeholder="权重"
                    style="width: 100px;"
                  ></el-input-number>
                </div>
              </div>
              <el-button size="mini" type="primary" @click="addFactor" style="margin-top: 10px;">添加因子</el-button>
            </div>
          </el-form-item>
          
          <el-form-item label="权重配置">
            <el-input 
              v-model="selectedFactor.weightConfig" 
              type="textarea" 
              placeholder="输入权重配置（JSON格式）"
              :rows="4"
            ></el-input>
            <div class="weight-help">
              <el-button size="mini" @click="showWeightHelp">权重说明</el-button>
              <el-button size="mini" @click="generateWeightConfig">生成权重</el-button>
            </div>
          </el-form-item>
          
          <el-form-item label="算法参数">
            <el-input 
              v-model="selectedFactor.algorithmParams" 
              type="textarea" 
              placeholder="输入算法参数（JSON格式）"
              :rows="4"
            ></el-input>
            <div class="param-help">
              <el-button size="mini" @click="showParamHelp">参数说明</el-button>
            </div>
          </el-form-item>
          
          <el-form-item label="计算周期">
            <el-select v-model="selectedFactor.calculationPeriod" placeholder="选择计算周期">
              <el-option label="日频" value="DAILY"></el-option>
              <el-option label="周频" value="WEEKLY"></el-option>
              <el-option label="月频" value="MONTHLY"></el-option>
              <el-option label="季频" value="QUARTERLY"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="回溯期数">
            <el-input-number 
              v-model="selectedFactor.lookbackPeriod" 
              :min="1" 
              :max="252"
              placeholder="输入回溯期数"
            ></el-input-number>
          </el-form-item>
          
          <el-form-item label="状态">
            <el-switch v-model="selectedFactor.enabled"></el-switch>
          </el-form-item>
          
          <el-form-item label="描述">
            <el-input 
              v-model="selectedFactor.description" 
              type="textarea" 
              placeholder="输入因子描述"
              :rows="3"
            ></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveFactor" :loading="saving">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 权重说明对话框 -->
    <el-dialog v-model="weightHelpVisible" title="权重配置说明" width="600px">
      <div class="weight-help-content">
        <div v-for="style in styleWeightConfigs" :key="style.type" class="style-help">
          <h4>{{ style.name }}</h4>
          <p>{{ style.description }}</p>
          <div class="weight-example">
            <strong>权重示例：</strong>
            <pre>{{ style.example }}</pre>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 参数说明对话框 -->
    <el-dialog v-model="paramHelpVisible" title="算法参数说明" width="600px">
      <div class="param-help-content">
        <div v-for="algorithm in algorithmParameters" :key="algorithm.type" class="algorithm-help">
          <h4>{{ algorithm.name }}</h4>
          <p>{{ algorithm.description }}</p>
          <div class="param-example">
            <strong>参数示例：</strong>
            <pre>{{ algorithm.example }}</pre>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 测试结果对话框 -->
    <el-dialog v-model="testResultVisible" title="测试计算结果" width="800px">
      <div class="test-result-content">
        <div class="result-summary">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="result-item">
                <div class="result-label">计算状态</div>
                <div class="result-value" :class="testResult.success ? 'success' : 'error'">
                  {{ testResult.success ? '成功' : '失败' }}
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="result-item">
                <div class="result-label">数据点数</div>
                <div class="result-value">{{ testResult.dataPoints || 0 }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="result-item">
                <div class="result-label">计算耗时</div>
                <div class="result-value">{{ testResult.duration || 0 }}ms</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="result-item">
                <div class="result-label">风格暴露</div>
                <div class="result-value">{{ testResult.styleExposure || 0 }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
        
        <div v-if="testResult.error" class="error-message">
          <strong>错误信息：</strong>
          <pre>{{ testResult.error }}</pre>
        </div>
        
        <div v-if="testResult.sampleData" class="sample-data">
          <h4>样本数据：</h4>
          <el-table :data="testResult.sampleData" height="300">
            <el-table-column prop="date" label="日期" width="100"></el-table-column>
            <el-table-column prop="value" label="风格因子值" width="120"></el-table-column>
            <el-table-column prop="fundCode" label="基金代码" width="100"></el-table-column>
            <el-table-column prop="styleScore" label="风格得分" width="100"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 计算结果显示弹窗 -->
    <el-dialog
        v-model="calculationResultVisible"
        title="风格因子计算结果"
        width="600px"
        :close-on-click-modal="false"
    >
      <div v-if="calculationResult" class="calculation-result">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="因子名称">
            {{ calculationResult.factorName }}
          </el-descriptions-item>
          <el-descriptions-item label="因子代码">
            {{ calculationResult.factorCode }}
          </el-descriptions-item>
          <el-descriptions-item label="基金代码">
            {{ calculationResult.fundCode }}
          </el-descriptions-item>
          <el-descriptions-item label="因子值">
            <span class="factor-value">{{ calculationResult.factorValue }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="计算时间">
            {{ formatDate(calculationResult.calculationTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="计算状态">
            <el-tag :type="calculationResult.success ? 'success' : 'danger'">
              {{ calculationResult.success ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <div v-if="!calculationResult.success && calculationResult.errorMessage" class="error-message" style="color: red; margin-top: 16px;">
          <strong>错误信息：</strong>
          <pre>{{ calculationResult.errorMessage }}</pre>
        </div>
        <div v-if="calculationResult.inputData" class="input-data-section">
          <h4>输入因子数据</h4>
          <el-table :data="calculationResult.inputData" size="small" border>
            <el-table-column prop="factorName" label="因子名称" width="150"></el-table-column>
            <el-table-column prop="factorValue" label="因子值" width="120"></el-table-column>
            <el-table-column prop="weight" label="权重" width="80"></el-table-column>
          </el-table>
        </div>

        <div v-if="calculationResult.calculationSteps" class="calculation-steps">
          <h4>计算步骤</h4>
          <el-steps :active="calculationResult.calculationSteps.length" direction="vertical" size="small">
            <el-step 
              v-for="(step, index) in calculationResult.calculationSteps" 
              :key="index"
              :title="step.title"
              :description="step.description"
            ></el-step>
          </el-steps>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="calculationResultVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="saveCalculationResult" 
            :loading="savingCalculation"
            :disabled="!calculationResult || !calculationResult.success"
          >
            保存到数据库
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from "axios";

export default {
  name: 'StyleFactor',
  setup() {
    // 响应式数据
    const factors = ref([])
    const selectedFactor = ref({})
    const searchFilters = ref({
      name: '',
      code: '',
      styleType: '',
      algorithm: '',
      enabled: null
    })
    const saving = ref(false)
    const calculating = ref(false)
    const testing = ref(false)
    const savingCalculation = ref(false)
    const weightHelpVisible = ref(false)
    const paramHelpVisible = ref(false)
    const testResultVisible = ref(false)
    const calculationResultVisible = ref(false)
    const testResult = ref({})
    const calculationResult = ref({})
    
    const availableFactors = ref([
      { code: '简单收益率因子', name: '简单收益率因子' },
      { code: '年化收益率因子', name: '年化收益率因子' },
      { code: '对数收益率因子', name: '对数收益率因子' },
      { code: '波动率因子', name: '波动率因子'},
      { code: '夏普比率因子', name: '夏普比率因子' },
      { code: '最大回撤因子', name: '最大回撤因子' },
      { code: '下行风险因子', name: '下行风险因子' },
      { code: '相对强弱指数因子', name: '相对强弱指数因子' },
      { code: '移动平均值因子', name: '移动平均值因子' },
      { code: '申购开放频率因子', name: '申购开放频率因子' },
      { code: '赎回开放频率因子', name: '赎回开放频率因子' }
    ])
    
    const styleWeightConfigs = ref([
      {
        type: 'VALUE',
        name: '价值风格',
        description: '基于估值指标构建的价值风格因子',
        example: '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'GROWTH',
        name: '成长风格',
        description: '基于增长指标构建的成长风格因子',
        example: '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'QUALITY',
        name: '质量风格',
        description: '基于质量指标构建的质量风格因子',
        example:'{"weights": [0.5, 0.5]}'
      },
      {
        type: 'MOMENTUM',
        name: '动量风格',
        description: '基于价格动量构建的动量风格因子',
        example:'{"weights": [0.5, 0.5]}'
      },
      {
        type: 'SIZE',
        name: '规模风格',
        description: '基于市值规模构建的规模风格因子',
        example: '{"weights": [0.5, 0.5]}'
      }
    ])
    
    const algorithmParameters = ref([
      {
        type: 'ADD',
        name: '加法',
        description: '对多个因子进行加法运算',
        example: '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'SUBTRACT',
        name: '减法',
        description: '对多个因子进行减法运算',
        example: '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'MULTIPLY',
        name: '乘法',
        description: '对多个因子进行乘法运算',
        example: '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'DIVIDE',
        name: '除法',
        description: '对多个因子进行除法运算',
        example: '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'WEIGHTED_MEAN',
        name: '加权平均',
        description: '对多个因子进行加权平均',
        example:  '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'ZSCORE',
        name: '标准化',
        description: '对因子进行Z-score标准化',
        example:  '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'WINSORIZE',
        name: '缩尾处理',
        description: '对因子进行缩尾处理',
        example:  '{"weights": [0.5, 0.5]}'
      },
      {
        type: 'PCA',
        name: '主成分分析',
        description: '对多个因子进行PCA降维',
        example: '{"weights": [0.5, 0.5]}'
      }
    ])
    
    // 计算属性
    const filteredFactors = computed(() => {
      if (!searchFilters.value.name && !searchFilters.value.code && !searchFilters.value.styleType && !searchFilters.value.algorithm && searchFilters.value.enabled === null) return factors.value
      return factors.value.filter(factor => 
        (searchFilters.value.name ? factor.factorName && factor.factorName.includes(searchFilters.value.name) : true) &&
        (searchFilters.value.code ? factor.factorCode && factor.factorCode.includes(searchFilters.value.code) : true) &&
        (searchFilters.value.styleType ? factor.styleType === searchFilters.value.styleType : true) &&
        (searchFilters.value.algorithm ? factor.formula && factor.formula.includes(searchFilters.value.algorithm) : true) &&
        (searchFilters.value.enabled !== null ? factor.enabled === searchFilters.value.enabled : true)
      )
    })
    
    // 方法
    const loadFactors = async () => {
      try {
        const response = await axios.get('http://localhost:8080/style/style-factor/noPage')
        factors.value = response.data
        console.log(response.data)
      } catch (error) {
        ElMessage.error('加载风格因子列表失败')
      }
    }
    const selectFactor = (factor) => {
      selectedFactor.value = { ...factor }
    }
    const createFactor = () => {
      selectedFactor.value = {
        factorName: '',
        factorCode: '',
        styleType: '',
        algorithm: '',
        baseFactors: [],
        operators: [],
        weights: [],
        weightConfig: '',
        algorithmParams: '',
        calculationPeriod: 'MONTHLY',
        lookbackPeriod: 60,
        enabled: true,
        description: ''
      }
    }
    
    const editFactor = (factor) => {
      selectedFactor.value = { ...factor }
    }
    
    const deleteFactor = async (factor) => {
      const id = factor.id || factor;
      ElMessageBox.confirm('确认删除?', '提示', { type: 'warning' })
        .then(async () => {
          await axios.delete(`http://localhost:8080/style/Style/deleteById/${id}`);
          await loadFactors();
        });
    }
    
    const saveFactor = async () => {
      if (!selectedFactor.value.factorName || !selectedFactor.value.factorCode) {
        ElMessage.warning('请填写因子名称和因子代码')
        return
      }

      saving.value = true
      try {
        // 构建请求数据
        const factorData = {
          name: selectedFactor.value.factorName,
          factorCode: selectedFactor.value.factorCode,
          description: selectedFactor.value.description || '',
          factorType: selectedFactor.value.styleType || 'GROWTH',
          algorithm: selectedFactor.value.operators && selectedFactor.value.operators.length > 0 
            ? selectedFactor.value.operators[0] 
            : 'ADD', // 默认使用第一个算子作为主算法
          algorithmParams: selectedFactor.value.algorithmParams || '{}',
          weightsConfig: JSON.stringify({
            weights: selectedFactor.value.weights || [],
            operators: selectedFactor.value.operators || [],
            factors: selectedFactor.value.baseFactors.map((factor, index) => ({
              factorCode: factor,
              factorName: getFactorName(factor),
              operator: selectedFactor.value.operators[index] || 'ADD',
              weight: selectedFactor.value.weights[index] || (1.0 / selectedFactor.value.baseFactors.length)
            }))
          }),
          baseFactors: selectedFactor.value.baseFactors || [],
          calculationPeriod: selectedFactor.value.calculationPeriod || 'MONTHLY',
          lookbackPeriod: selectedFactor.value.lookbackPeriod || 60,
          enabled: selectedFactor.value.enabled !== undefined ? selectedFactor.value.enabled : true
        }

        console.log('保存风格因子数据:', factorData); // 调试日志

        let response
        if (selectedFactor.value.id) {
          // 更新
          response = await axios.put(`http://localhost:8080/style/upData/styleFactor`, factorData)
        } else {
          // 创建
          response = await axios.post('http://localhost:8080/style/create/styleFactor', factorData)
        }

        if (response.data) {
          ElMessage.success('保存成功')
          await loadFactors()
          // 清空表单
          selectedFactor.value = {}
        } else {
          ElMessage.error('保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        if (error.response && error.response.data && error.response.data.error) {
          ElMessage.error(error.response.data.error)
        } else {
          ElMessage.error('保存失败，请检查网络连接')
        }
      } finally {
        saving.value = false
      }
    }
    
    const resetForm = () => {
      selectedFactor.value = {}
    }
    const exportFactors = () => {
      const dataStr = JSON.stringify(factors.value, null, 2)
      const dataBlob = new Blob([dataStr], { type: 'application/json' })
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'style_factors.json'
      link.click()
      URL.revokeObjectURL(url)
    }

    const calculateFactor = async (row) => {
      console.log("calculateFactor called with row:", row); // 调试信息
      if (!row.fundCode) {
        ElMessage.warning('请输入基金代码');
        return;
      }
      
      try {
        calculating.value = true;
        const response = await axios.post(`http://localhost:8080/style/${row.factorCode}/${row.fundCode}/calculate`);
        
        if (response.data && response.data.success) {
          // 构建计算结果对象
          calculationResult.value = {
            factorName: row.factorName,
            factorCode: row.factorCode,
            fundCode: row.fundCode,
            factorValue: response.data.factorValue,
            calculationTime: new Date(),
            success: true,
            inputData: [
              // 这里可以根据实际返回的数据构建输入因子数据
              { factorName: '输入因子1', factorValue: '0.123', weight: '0.5' },
              { factorName: '输入因子2', factorValue: '0.456', weight: '0.5' }
            ],
            calculationSteps: [
              { title: '获取输入因子数据', description: '成功获取2个输入因子的数据' },
              { title: '应用权重', description: '对输入因子应用权重配置' },
              { title: '执行计算', description: `使用${row.formula || 'ADD'}算法进行计算` },
              { title: '生成结果', description: `计算完成，因子值: ${response.data.factorValue}` }
            ]
          };
          
          // 显示计算弹窗
          calculationResultVisible.value = true;
        } else {
          // 构建错误结果对象
          calculationResult.value = {
            factorName: row.factorName,
            factorCode: row.factorCode,
            fundCode: row.fundCode,
            factorValue: null,
            calculationTime: new Date(),
            success: false,
            errorMessage: response.data.message || '未知错误'
          };
          
          // 显示计算弹窗
          calculationResultVisible.value = true;
        }
      } catch (error) {
        console.error('计算失败:', error);
        let errorMsg = '计算失败';
        
        if (error.response?.data?.message) {
          errorMsg = error.response.data.message;
        } else if (error.response?.status === 400) {
          errorMsg = '请求参数错误';
        } else if (error.response?.status === 404) {
          errorMsg = '风格因子或基金代码不存在';
        } else if (error.response?.status === 500) {
          errorMsg = '服务器内部错误';
        } else if (error.message) {
          errorMsg = error.message;
        }
        
        // 构建错误结果对象
        calculationResult.value = {
          factorName: row.factorName,
          factorCode: row.factorCode,
          fundCode: row.fundCode,
          factorValue: null,
          calculationTime: new Date(),
          success: false,
          errorMessage: errorMsg
        };
        
        // 显示计算弹窗
        calculationResultVisible.value = true;
      } finally {
        calculating.value = false;
      }
    };

    const saveCalculationResult = async () => {
      if (!calculationResult.value || !calculationResult.value.success) {
        ElMessage.warning('没有有效的计算结果可以保存');
        return;
      }

      savingCalculation.value = true;
      try {
        const saveData = {
          factorCode: calculationResult.value.factorCode,
          fundCode: calculationResult.value.fundCode,
          factorValue: calculationResult.value.factorValue,
          calculationTime: calculationResult.value.calculationTime
        };

        const response = await axios.post('http://localhost:8080/style/style-factor/save-calculation-result', saveData);
        
        if (response.data && response.data.success) {
          ElMessage.success('计算结果已保存到数据库');
          calculationResultVisible.value = false;
        } else {
          ElMessage.error(`保存失败: ${response.data.message || '未知错误'}`);
        }
      } catch (error) {
        console.error('保存计算结果失败:', error);
        const errorMsg = error.response?.data?.message || error.message || '保存失败';
        ElMessage.error(`保存计算结果失败: ${errorMsg}`);
      } finally {
        savingCalculation.value = false;
      }
    };
    
    const onStyleTypeChange = () => {
      // 根据风格类型设置默认权重配置
      const style = styleWeightConfigs.value.find(s => s.type === selectedFactor.value.styleType)
      if (style) {
        selectedFactor.value.weightConfig = style.example
      }
    }
    
    const onAlgorithmChange = () => {
      // 根据算法类型设置默认参数
      const algorithm = algorithmParameters.value.find(a => a.type === selectedFactor.value.algorithm)
      if (algorithm) {
        selectedFactor.value.algorithmParams = algorithm.example
      }
    }
    
    const showWeightHelp = () => {
      weightHelpVisible.value = true
    }
    
    const showParamHelp = () => {
      paramHelpVisible.value = true
    }
    
    const getStyleTagType = (styleType) => {
      const typeMap = {
        'VALUE': 'primary',
        'GROWTH': 'success',
        'QUALITY': 'warning',
        'MOMENTUM': 'danger',
        'SIZE': 'info',
        'ESG': 'success',
        'LOW_VOLATILITY': 'warning',
        'HIGH_DIVIDEND': 'primary',
        'TECHNOLOGY': 'danger',
        'CONSUMER': 'success',
        'CUSTOM': 'info'
      }
      return typeMap[styleType] || 'info'
    }
    
    const getStyleName = (styleType) => {
      const nameMap = {
        'VALUE': '价值',
        'GROWTH': '成长',
        'QUALITY': '质量',
        'MOMENTUM': '动量',
        'SIZE': '规模',
        'ESG': 'ESG',
        'LOW_VOLATILITY': '低波动',
        'HIGH_DIVIDEND': '高股息',
        'TECHNOLOGY': '科技',
        'CONSUMER': '消费',
        'CUSTOM': '自定义'
      }
      return nameMap[styleType] || styleType
    }
    
    const getAlgorithmName = (algorithm) => {
      const nameMap = {
        'ADD': '加法',
        'SUBTRACT': '减法',
        'MULTIPLY': '乘法',
        'DIVIDE': '除法',
        'MEAN': '均值',
        'WEIGHTED_MEAN': '加权平均',
        'STD': '标准差',
        'VARIANCE': '方差',
        'MEDIAN': '中位数',
        'RANK': '排序',
        'ZSCORE': '标准化',
        'WINSORIZE': '缩尾',
        'LOG': '对数',
        'DIFF': '差分',
        'PCA': 'PCA',
        'FACTOR_ANALYSIS': '因子分析',
        'CLUSTERING': '聚类',
        'REGRESSION': '回归'
      }
      return nameMap[algorithm] || algorithm
    }
    
    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleString()
    }
    
    const onSearch = () => {
      loadFactors()
    }
    
         // 多因子支持方法
     const onBaseFactorsChange = () => {
       const factors = selectedFactor.value.baseFactors || [];
       const currentOperators = selectedFactor.value.operators || [];
       const currentWeights = selectedFactor.value.weights || [];
       
       // 调整算子数组长度
       while (currentOperators.length < factors.length) {
         currentOperators.push('ADD');
       }
       while (currentOperators.length > factors.length) {
         currentOperators.pop();
       }
       
       // 调整权重数组长度
       while (currentWeights.length < factors.length) {
         currentWeights.push(1.0 / factors.length);
       }
       while (currentWeights.length > factors.length) {
         currentWeights.pop();
       }
       
       // 重新计算权重，确保总和为1
       if (currentWeights.length > 0) {
         const totalWeight = currentWeights.reduce((sum, weight) => sum + weight, 0);
         if (totalWeight !== 1) {
           currentWeights.forEach((weight, index) => {
             currentWeights[index] = weight / totalWeight;
           });
         }
       }
       
       selectedFactor.value.operators = currentOperators;
       selectedFactor.value.weights = currentWeights;
       
       // 生成新的权重配置
       generateWeightConfig();
     }
     
     const removeFactor = (index) => {
       selectedFactor.value.baseFactors.splice(index, 1);
       onBaseFactorsChange();
     }
     
     const addFactor = () => {
       if (!selectedFactor.value.baseFactors) {
         selectedFactor.value.baseFactors = [];
       }
       selectedFactor.value.baseFactors.push('');
       onBaseFactorsChange();
     }

     const getFactorName = (factorCode) => {
       const factor = availableFactors.value.find(f => f.code === factorCode);
       return factor ? factor.name : factorCode;
     }

     const generateWeightConfig = () => {
       const factors = selectedFactor.value.baseFactors || [];
       const operators = selectedFactor.value.operators || [];
       const weights = selectedFactor.value.weights || [];
       
       const config = {
         factors: factors.map((factor, index) => ({
           factorCode: factor,
           factorName: getFactorName(factor),
           operator: operators[index] || 'ADD',
           weight: weights[index] || (1.0 / factors.length)
         })),
         weights: weights,
         operators: operators
       };
       
       selectedFactor.value.weightConfig = JSON.stringify(config, null, 2);
     }
    
    // 生命周期
    onMounted(() => {
      loadFactors()
    })
    
    return {
      factors,
      selectedFactor,
      searchFilters,
      saving,
      calculating,
      testing,
      savingCalculation,
      weightHelpVisible,
      paramHelpVisible,
      testResultVisible,
      calculationResultVisible,
      testResult,
      calculationResult,
      availableFactors,
      styleWeightConfigs,
      algorithmParameters,
      filteredFactors,
      
      loadFactors,
      selectFactor,
      createFactor,
      editFactor,
      deleteFactor,
      saveFactor,
      calculateFactor,
      saveCalculationResult,
      resetForm,
      exportFactors,
      onStyleTypeChange,
      onAlgorithmChange,
      showWeightHelp,
      showParamHelp,
      getStyleTagType,
      getStyleName,
      getAlgorithmName,
      formatDate,
             onSearch,
       onBaseFactorsChange,
       removeFactor,
       addFactor,
       getFactorName,
       generateWeightConfig
    }
  }
}
</script>

<style scoped>
.style-factor-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 20px;
  height: calc(100vh - 120px);
}

.factor-list {
  width: 60%;
  border: 1px solid #ddd;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  background: #f9f9f9;
}

.list-header h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.search-filters {
  margin-top: 10px;
}

.search-filters .el-row {
  margin-bottom: 10px;
}

.search-filters .el-col {
  margin-bottom: 5px;
}

.factor-config {
  width: 40%;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 20px;
  background: #fafafa;
  overflow-y: auto;
}

.factor-config h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.factor-form {
  background: white;
  padding: 20px;
  border-radius: 4px;
  border: 1px solid #eee;
}

.weight-help,
.param-help {
  margin-top: 5px;
}

.weight-help-content,
.param-help-content {
  max-height: 400px;
  overflow-y: auto;
}

.style-help,
.algorithm-help {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.style-help h4,
.algorithm-help h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.style-help p,
.algorithm-help p {
  margin: 0 0 10px 0;
  color: #666;
}

.weight-example,
.param-example {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
}

.weight-example pre,
.param-example pre {
  margin: 0;
  font-size: 12px;
}

.test-result-content {
  max-height: 500px;
  overflow-y: auto;
}

.result-summary {
  margin-bottom: 20px;
}

.result-item {
  text-align: center;
  padding: 10px;
  background: #f9f9f9;
  border-radius: 4px;
}

.result-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

.result-value {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.result-value.success {
  color: #67c23a;
}

.result-value.error {
  color: #f56c6c;
}

.error-message {
  margin: 15px 0;
  padding: 10px;
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
  color: #f56c6c;
}

.error-message pre {
  margin: 10px 0 0 0;
  font-size: 12px;
}

.sample-data {
  margin-top: 20px;
}

.sample-data h4 {
  margin: 0 0 10px 0;
  color: #333;
}

/* 计算弹窗样式 */
.calculation-result {
  padding: 10px 0;
}

.factor-value {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.input-data-section,
.calculation-steps {
  margin-top: 20px;
}

.input-data-section h4,
.calculation-steps h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.factor-count-info {
  margin-top: 10px;
  font-size: 12px;
  color: #666;
}

.operator-config {
  margin-top: 10px;
}

.operator-item {
  margin-bottom: 10px;
}

.operator-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.operator-content {
  display: flex;
  align-items: center;
}

.factor-name {
  margin-right: 10px;
}
</style> 